package com.hoshiicloud.market.controller.market;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.market.entity.market.Coupons;
import com.hoshiicloud.market.param.market.CouponsAddParam;
import com.hoshiicloud.market.param.market.CouponsQueryParam;
import com.hoshiicloud.market.param.market.CouponsUpdateParam;
import com.hoshiicloud.market.service.market.CouponsService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 系统优惠券 控制器
 * </p>
 *
 * @author campchen
 * @since 2019-05-14
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/coupons")
@Api(value = "营销服务", tags = {"系统优惠券管理"})
public class CouponsController {
    @Autowired
    private CouponsService couponsService;

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 分页查询系统优惠券
    */
    @ApiOperation(value = "分页查询系统优惠券")
    @PostMapping("/query/page")
    public Response page(@RequestBody @Valid CouponsQueryParam param) {
        try {
            log.info("分页查询系统优惠券");
            QueryWrapper<Coupons> queryWrapper = new QueryWrapper<Coupons>();
            queryWrapper.eq(param.getConmpanyid() != null, "conmpanyid", param.getConmpanyid());
            queryWrapper.eq(param.getPlatformid() != null, "platformid", param.getPlatformid());
            queryWrapper.eq(param.getStoreid() != null, "storeid", param.getStoreid());
            queryWrapper.eq(StringUtils.isNotBlank(param.getCouponNo()), "coupon_no", param.getCouponNo());
            queryWrapper.eq(StringUtils.isNotBlank(param.getCouponQrcode()), "coupon_qrcode", param.getCouponQrcode());
            queryWrapper.eq(param.getCouponName() != null, "coupon_name", param.getCouponName());
            queryWrapper.eq(param.getCredit() != null, "credit", param.getCredit());
            queryWrapper.eq(param.getAmount() != null, "amount", param.getAmount());
            queryWrapper.eq(param.getDiscount() != null, "discount", param.getDiscount());
            queryWrapper.eq(param.getFromDate() != null, "from_date", param.getFromDate());
            queryWrapper.eq(param.getGotDates() != null, "got_dates", param.getGotDates());
            queryWrapper.eq(param.getToDate() != null, "to_date", param.getToDate());
            queryWrapper.eq(param.getDeleted() != null, "deleted", param.getDeleted());
            queryWrapper.eq(StringUtils.isNotBlank(param.getRemark()), "remark", param.getRemark());
            queryWrapper.eq(param.getOrderid() != null, "orderid", param.getOrderid());
            queryWrapper.eq(param.getMemberid() != null, "memberid", param.getMemberid());
            IPage<Coupons> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            queryWrapper.select(BeanUtils.getSqlSelect(Coupons.class));
            return Response.data(couponsService.page(page, queryWrapper));
          } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
          } catch (Exception e) {
            log.error("分页查询系统优惠券异常", e);
            return Response.failed("分页查询系统优惠券异常");
        }
    }
    /**
    * @param id
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 根据id查询系统优惠券
    */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询系统优惠券")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(couponsService.getById(id));
    }

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 新增
    */
    @PostMapping("/save")
    @ApiOperation(value = "新增系统优惠券 如添加人为租户人员则不传平台id、店铺id；如添加人员为平台人员则不传店铺id；")
    public Response save(/*@RequestBody*/ @Valid CouponsAddParam param) {
        try {
            /*
            * 此段为判断添加人属于哪个机构，且限制其添加信息区域
            * */
            Coupons data = BeanUtils.covertType(param, Coupons.class);
            return Response.data(couponsService.save(data));
        } catch (ServiceException e) {
            log.error("新增系统优惠券异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("新增系统优惠券异常", e);
            return Response.failed();
        }
    }

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 修改系统优惠券
    */
    @PutMapping("/update")
    @ApiOperation(value = "修改系统优惠券")
    public Response update(@RequestBody @Valid CouponsUpdateParam param) {
        try {
            Coupons coupons=couponsService.getById(param.getId());
            //如果是店铺优惠卷，则不能修改租户id和平台id
            if (coupons.getStoreid()>0){
                param.setConmpanyid(null);
                param.setPlatformid(null);
            }
            //如果是平台优惠卷，则不能修改租户id
            else if (coupons.getPlatformid()>0){
                param.setConmpanyid(null);
            }
            Coupons data = BeanUtils.covertType(param, Coupons.class);
            return Response.data(couponsService.updateById(data));
        }catch (ServiceException e) {
            log.error("修改系统优惠券异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("修改系统优惠券异常", e);
            return Response.failed();
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除系统优惠券
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除系统优惠券")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        try {
            /*
            * 判断人员属于那层机构，赋予不同权限。如店铺，值能删除店铺id为此人所属id的优惠卷。
            * 平台人员（本平台以及其下店铺），租户人员（本租户及其下所有平台）
            * */
            Coupons data=couponsService.getById(id);
            if(data==null){
                log.error("删除系统优惠券异常，无法找到系统优惠券记录");
                return Response.failed("删除系统优惠券异常，无法找到系统优惠券记录");
            }
            couponsService.deleteById(data);
            return Response.success("删除系统优惠券成功");
        }catch (ServiceException e) {
            log.error("删除系统优惠券异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("删除系统优惠券异常", e);
            return Response.failed();
        }
    }

}
